<template>
  <div class="main-container">
    <AddUserStockView ref="addUserStockViewRef" @refreshZixuanStatus="refreshStockInZixuanStatus" />
    <Spin tip="Loading..." style="position: absolute;top:42%; left:45%;" :spinning="showLoading" />
    <div class="h-header">
      <div style="display: flex;">
        <button class="filter-button active">
          <div class="flex" style="display: flex; flex-direction: row; justify-content: center; align-items: center;">
            <svg v-if="paneType == 0" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
              fill="none" version="1.1" width="16" height="16" viewBox="0 0 16 16">
              <defs>
                <clipPath id="master_svg0_909_01793">
                  <rect x="0" y="0" width="16" height="16" rx="0" />
                </clipPath>
              </defs>
              <g clip-path="url(#master_svg0_909_01793)">
                <g>
                  <rect x="1" y="2" width="1" height="13" rx="0" fill="#025FFF" fill-opacity="1" />
                </g>
                <g>
                  <rect x="14" y="2" width="1" height="13" rx="0" fill="#025FFF" fill-opacity="1" />
                </g>
                <g>
                  <rect x="4" y="10" width="2" height="4" rx="0" fill="#025FFF" fill-opacity="1" />
                </g>
                <g>
                  <rect x="7" y="6" width="2" height="6" rx="0" fill="#025FFF" fill-opacity="1" />
                </g>
                <g>
                  <rect x="10" y="3" width="2" height="4" rx="0" fill="#025FFF" fill-opacity="1" />
                </g>
              </g>
            </svg>
            <svg v-if="paneType == 1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
              fill="none" version="1.1" width="16" height="16" viewBox="0 0 16 16">
              <defs>
                <clipPath id="master_svg0_909_01793">
                  <rect x="0" y="0" width="16" height="16" rx="0" />
                </clipPath>
              </defs>
              <g clip-path="url(#master_svg0_909_01793)">
                <g>
                  <rect x="1" y="2" width="1" height="13" rx="0" fill="#212123" fill-opacity="1" />
                </g>
                <g>
                  <rect x="14" y="2" width="1" height="13" rx="0" fill="#212123" fill-opacity="1" />
                </g>
                <g>
                  <rect x="4" y="10" width="2" height="4" rx="0" fill="#212123" fill-opacity="1" />
                </g>
                <g>
                  <rect x="7" y="6" width="2" height="6" rx="0" fill="#212123" fill-opacity="1" />
                </g>
                <g>
                  <rect x="10" y="3" width="2" height="4" rx="0" fill="#212123" fill-opacity="1" />
                </g>
              </g>
            </svg>
            <span class="flex" style="margin-left: 5px;">区间统计</span>
          </div>
        </button>
        <button class="filter-button" style="margin-left: 1em;">
          <div class="flex" style="display: flex; flex-direction: row; justify-content: center; align-items: center;">
            <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1"
              width="12" height="13.333333969116211" viewBox="0 0 12 13.333333969116211">
              <g>
                <path
                  d="M0.666667,0L11.3333,0C11.7015,0,12,0.298477,12,0.666667L12,12.6667C12,13.0349,11.7015,13.3333,11.3333,13.3333L0.666667,13.3333C0.298477,13.3333,0,13.0349,0,12.6667L0,0.666667C0,0.298477,0.298477,0,0.666667,0ZM2.66667,6.66667L2.66667,8L4,8L4,6.66667L2.66667,6.66667ZM2.66667,9.33333L2.66667,10.6667L4,10.6667L4,9.33333L2.66667,9.33333ZM5.33333,6.66667L5.33333,8L6.66667,8L6.66667,6.66667L5.33333,6.66667ZM5.33333,9.33333L5.33333,10.6667L6.66667,10.6667L6.66667,9.33333L5.33333,9.33333ZM8,6.66667L8,10.6667L9.33333,10.6667L9.33333,6.66667L8,6.66667ZM2.66667,2.66667L2.66667,5.33333L9.33333,5.33333L9.33333,2.66667L2.66667,2.66667Z"
                  fill-opacity="1" />
              </g>
            </svg>
            <span class="flex" style="margin-left: 5px;">历史数据回测</span>
          </div>
        </button>
      </div>
      <div style="display: flex;margin-left: auto;">
        <a-input placeholder="搜索股票代码" size="large" v-model:value="searchStockCode"
          style="width: 300px; border-radius: 8px;" @pressEnter="onSearch">
          <template #prefix>
            &nbsp;<search-outlined style="color:#919191;" />
          </template>
        </a-input>
      </div>

    </div>
    <div class="h-form">
      <a-radio-group v-model:value="sortType" @change="sortTypeChange" style="margin-top: 3px;">
        <a-radio :value="1">板块区间幅度排名</a-radio>
        <a-radio :value="2">个股区间幅度排名</a-radio>
      </a-radio-group>
      <div style="margin-left: 3em;">
        起始日期：<a-date-picker v-model:value="startTime" value-format="YYYY-MM-DD"
          placeholder="请选择开始时间" style="width:150px;border-radius: 8px;
        background-color: #fafafa;" />&nbsp;&nbsp;
        结束日期：<a-date-picker v-model:value="endTime" value-format="YYYY-MM-DD"
          placeholder="请选择结束时间" style="width:150px;border-radius: 8px;
        background-color: #fafafa;" />
      </div>
      <div style="margin-left:1em">
        <a-button type="primary" @click="searchStockOrSector">查询</a-button>
      </div>

    </div>

    <div class="h-body" >
      <div class="flex left-list">
        <div class="s-table">
          <div class="flex s-head">
            <div class="flex">名称代码</div>
            <div class="flex stock-close">股价</div>
            <div class="flex">涨跌幅</div>
          </div>
          <div class="flex s-body" id="leftList">
            <div :class="{ 'flex': true, 's-row': true, 'selected': item.selected }" v-for="item in leftDataSource"
              :key="item.id" @click="leftDataItemClick(item)">
              <div class="flex" style="flex-direction: column;">
                <div class="s-body-stock-name">{{ item.name }}</div>
              </div>
              <div class="flex stock-close">
                <div v-if="item.riseAndFall > 0" class="stock-text-red">{{ item.close }}</div>
                <div v-else class="stock-text-green">{{ item.close }}</div>
              </div>
              <div class="flex">
                <div v-if="item.riseAndFall > 0" class="stock-text-red">+{{ item.riseAndFall }}%</div>
                <div v-else class="stock-text-green">-{{ item.riseAndFall }}%</div>
              </div>
            </div>
          </div>
        </div>
      </div>


      <div class="right-list flex">
        <div class="s-table">
          <div class="flex s-head">
            <div class="flex">
              <span v-if="sortType == 1">板块个股</span>
              <span v-if="sortType == 2">个股板块</span>
            </div>
            <div class="flex stock-close">股价</div>
            <div class="flex">涨跌幅</div>
          </div>
          <div class="flex s-body" id="rightList">
            <div :class="{ 'flex': true, 's-row': true, 'selected': item.selected }" v-for="item in rightDataSource"
              :key="item.id" @click="rightDataItemClick(item)">
              <div class="flex" style="flex-direction: column;">
                <div class="s-body-stock-name">{{ item.name }}</div>
              </div>
              <div class="flex stock-close">
                <div v-if="item.riseAndFall > 0" class="stock-text-red">{{ item.close }}</div>
                <div v-else class="stock-text-green">{{ item.close }}</div>
              </div>
              <div class="flex">
                <div v-if="item.riseAndFall > 0" class="stock-text-red">+{{ item.riseAndFall }}%</div>
                <div v-else class="stock-text-green">-{{ item.riseAndFall }}%</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="flex" style="flex: 3; " ref="screenShot">
        <div class="flex" style="flex-direction: column;width:100%;height:100%">
          <div style="display:flex; width:100%;height:100%;flex-direction: column;position: relative;">
            <div class="flex" style="flex:1.5; flex-direction: column;">
              <div class="flex s-head">
                <div>个股走势</div>
              </div>
              <div style="display: flex;border: 1px solid #f1f1f1;height: 48px;line-height: 48px;padding: 0 .5em;">
                <a-avatar style="width:24px;height: 24px; margin-top: 12px;" :src="currentStockData.logo" />
                <span
                class="stock-name">{{ currentStockData.stockName }}</span>
                <div class="k-line-name"></div>
                <div class="period">
                  <span :class="{active: currentPeriod=='Day'}" @click="switchPeriod('Day')">D</span>
                  <span :class="{active: currentPeriod=='Week'}" @click="switchPeriod('Week')">W</span>
                  <span :class="{active: currentPeriod=='Month'}" @click="switchPeriod('Month')">M</span>
                </div>
                <div class="setting-splitter"></div>
                <div class="k-line-setting ">
                  <a-button type="default" :icon="h(LineChartOutlined)" @click="openIndicatorSetting">指标</a-button>
                  <a-button type="default" :icon="h(SettingOutlined)" @click="openBaseSetting">设置</a-button>
                  <a-button type="default" :icon="h(FolderViewOutlined)" @click="screenShotEvent">截屏</a-button>
                </div>

                <div style="margin-left: auto;">
                  <span class="flex addUserStock" @click="addUserStocksClick" v-if="!stockInZixuanStatus"
                      style="flex-direction: row;justify-content: center;align-items: center;cursor: pointer;">
                      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="000000"
                        version="1.1" width="24" height="24" viewBox="0 0 24 24">
                        <defs>
                          <clipPath id="master_svg0_1457_13242">
                            <rect x="0" y="0" width="24" height="24" rx="0" />
                          </clipPath>
                        </defs>
                        <g clip-path="url(#master_svg0_1457_13242)">
                          <g>
                            <rect x="17" y="18" width="5" height="1" rx="0.5" fill-opacity="1" />
                          </g>
                          <g transform="matrix(0,1,-1,0,36,-4)">
                            <rect x="20" y="16" width="5" height="1" rx="0.5" fill-opacity="1" />
                          </g>
                          <g transform="matrix(1,0,0,-1,0,40)">
                            <path
                              d="M12,34.0171L13.048,35.122Q14.5295,36.683800000000005,16.6325,36.683800000000005Q18.7354,36.683800000000005,20.2169,35.122Q21.6838,33.5755,21.6838,31.3955Q21.6838,29.215519999999998,20.2169,27.66902L13.2217,20.294281Q12.72365,19.769253,12,19.769253Q11.27635,19.769253,10.77834,20.294281L3.783077,27.66902Q2.316174,29.215519999999998,2.316174,31.3955Q2.316174,33.5755,3.783087,35.122Q5.26459,36.683800000000005,7.36755,36.683800000000005Q9.47052,36.683800000000005,10.951979999999999,35.122L12,34.0171ZM16.6325,35.3162Q15.1173,35.3162,14.0403,34.1808L12.49614,32.5528Q12.40253,32.4542,12.27828,32.3988Q12.15403,32.3434,12.01805,32.3399Q11.88208,32.3363,11.75508,32.385Q11.62808,32.4337,11.5294,32.5273Q11.51629,32.539699999999996,11.50386,32.5528L9.959710000000001,34.1808Q8.88275,35.3162,7.36755,35.3162Q5.8523499999999995,35.3162,4.77534,34.1808Q3.683826,33.03,3.683826,31.3955Q3.683826,29.76097,4.7753499999999995,28.61023L11.77061,21.23549Q11.86412,21.13691,12,21.13691Q12.13588,21.13691,12.22939,21.23549L19.2247,28.61023Q20.3162,29.76098,20.3162,31.3955Q20.3162,33.03,19.2247,34.1808Q18.1477,35.3162,16.6325,35.3162Z"
                              fill-rule="evenodd" fill-opacity="1" />
                          </g>
                        </g>
                      </svg>
                      <span style="margin-left:3px">加自选</span>
                    </span>
                    
                    <span class="flex deleteUserStock" v-if="stockInZixuanStatus" @click="deleteUserStocksClick"
                      style="flex-direction: row;justify-content: center;align-items: center;cursor: pointer;">
                      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="#333333"
                        version="1.1" width="24" height="24" viewBox="0 0 24 24" class="flex">
                        <defs>
                          <clipPath id="master_svg0_1457_13402">  
                            <rect x="0" y="0" width="24" height="24" rx="0" />
                          </clipPath>
                        </defs>
                        <g clip-path="url(#master_svg0_1457_13402)">
                          <g>
                            <rect x="17" y="18" width="5" height="1" rx="0.5" fill-opacity="1" />
                          </g>
                          <g transform="matrix(1,0,0,-1,0,40)">
                            <path
                              d="M12,33.0234L10.45584,34.6514C8.75023,36.4495,5.98489,36.4495,4.27921,34.6514C2.573596,32.8532,2.573596,29.93779,4.27921,28.13963L11.27447,20.764886C11.66882,20.349144,12.33118,20.349144,12.72553,20.764886L19.7208,28.13963C21.4264,29.93779,21.4264,32.8532,19.7208,34.6514C18.0151,36.4495,15.2498,36.4495,13.5442,34.6514L12,33.0234Z"
                              fill-opacity="1" />
                          </g>
                        </g>
                      </svg>
                      <span style="margin-left:3px">删自选</span>
                    </span>
                </div>
              </div>

              <div :class="{'stock-chart-view': true}" >
                <chartView ref="chartViewRef" :stock="currentStockData" 
                    @settingChange="onSettingChange" @indicatorChange="onIndicatorChange"
                    :mainIndicators="selectedMainIndicator" :subIndicators="selectedSubIndicator"
                    :settingItems="settingItems" />
              </div>

            </div>


            <div style="display: flex; flex-direction: column;flex: 1">
              <div style="display:flex; width:100%;background-color: #fafafa;height: 32px;
                border-top: 1px solid #e5e5e5;border-bottom:1px solid #e5e5e5;
                color:#9E9E9E;padding-left:.5em;line-height: 32px;">
                <span style="display: inline-block;">板块走势-{{ currentSectorName }}</span>
                <!-- <span style="display:inline-block; float: right;margin-right: .5em;cursor: pointer;" 
                  title="点击关闭" @click="toggleChartView">
                  <EyeOutlined/>
                </span> -->
              </div>
  
            
              <div class="flex sector-chart-view" style="height: calc(100% - 32px);">
                <chartView2 ref="chartViewRef2" :stock="currentStockData"
                    @settingChange="onSettingChange" @indicatorChange="onIndicatorChange"
                    :mainIndicators="selectedMainIndicator" :subIndicators="selectedSubIndicator"
                    :settingItems="settingItems" />
              </div>
              
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script lang="ts">
import { message, Popconfirm, Drawer, Radio, Input, Select, Table, Avatar, 
  RadioGroup, Button, Modal, Checkbox, DatePicker } from 'ant-design-vue';
import { SearchOutlined, LineChartOutlined, SettingOutlined, FolderViewOutlined, 
    InsertRowRightOutlined, CaretLeftOutlined, EyeOutlined } from '@ant-design/icons-vue';
import { ref, onMounted, onUnmounted, defineProps, h } from 'vue';
import { right } from 'inquirer/lib/utils/readline';
import AddUserStockView from '../stock/add_user_stock.vue'
import dayjs, { Dayjs } from 'dayjs';
export default {
  components: {
    AButton: Button,
    ADrawer: Drawer,
    ARadio: Radio,
    AInput: Input,
    ASelect: Select,
    ATable: Table,
    AAvatar: Avatar,
    Popconfirm: Popconfirm,
    ARadioGroup: RadioGroup,
    AModal: Modal,
    ACheckbox: Checkbox,
    ADatePicker: DatePicker
  },
};
</script>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { Spin } from 'ant-design-vue'
import { StockOutlined } from '@ant-design/icons-vue';
import { getStocksOfDateRange } from '/@/api/stock/stockDailyDao';
import { getSectorOfDateRange, getSectorByName } from '/@/api/stock/sectorDailyDao';
import { stockInUserStock, deleteUserStock } from '/@/api/stock/userStocksDao';
import chartView from '../chart/chart_view_pure_stock.vue';
import chartView2 from '../chart/chart_view_pure_sector.vue';
import html2canvas from 'html2canvas';
import { getCurrentUserId } from '../../utils/currentUser.ts';

const showSectorChart = ref(true);
const currentPeriod = ref('Day');
const showLoading = ref(false);
const hBodyWidth = ref('520px');
const searchStockCode = ref('');
const startTime = ref(dayjs(getNowFormatDate(-30)).format('YYYY-MM-DD'));
const endTime = ref(dayjs(getNowFormatDate(0)).format('YYYY-MM-DD'))
const sortType = ref(1);
const leftDataSource = ref([]);
const rightDataSource = ref([]);
const paneType = ref(0);
const stockInZixuanStatus = ref(false);
const addUserStockViewRef = ref();

const chartViewRef = ref();
const chartViewRef2 = ref();
const currentSectorName = ref('');
const selectedSubIndicator = ref(['VOL']);
const selectedMainIndicator = ref(['stockWeighted252dRS']);
const drawerVisbile = ref(false);
const screenShot = ref();

function screenShotEvent(){
  html2canvas(screenShot.value).then((canvas)=>{
    const image = canvas.toDataURL('image/png');
    const downloadLink = document.createElement('a');
    downloadLink.href = image;
    downloadLink.download = 'screenshot.png';
    downloadLink.click();
  });
}

function switchPeriod(period){
  currentPeriod.value = period;
  chartViewRef.value.switchPeriod(period);
  chartViewRef2.value.switchPeriod(period);
}

function openIndicatorSetting() {
  indicatorSetting.value = true;
}

function cancelIndicatorSetting() {
  indicatorSetting.value = false;
}

function getNowFormatDate(offsetDays) {
  let date = new Date();
  date.setDate(date.getDate() + offsetDays);
  date = new Date(date);

  let year = date.getFullYear();
  let month = (date.getMonth() + 1).toString().padStart(2, '0');
  let day = date.getDate().toString().padStart(2, '0');
  return year + '-' + month +'-' + day;
}

const settingItems = ref([
  {
    name: "蜡烛图类型", type: "select", options: [
      { label: "全实心", value: "candle_solid" },
      { label: "全空心", value: "candle_stroke" },
      { label: "涨空心", value: "candle_up_stroke" },
      { label: "跌空心", value: "candle_down_stroke" },
      { label: "OHLC", value: "ohlc" },
      { label: "面积图", value: "area" }
    ],
    key: "candle.type",
    defaultValue: "candle_solid",
    value: "candle_solid"
  },
  { name: "最新价显示", type: "switch", options: [], key: "candle.priceMark.last.show", defaultValue: true, value: true },
  { name: "最高价显示", type: "switch", options: [], key: "candle.priceMark.high.show", defaultValue: true, value: true },
  { name: "最低价显示", type: "switch", options: [], key: "candle.priceMark.low.show", defaultValue: true, value: true },
  {
    name: "指标最新值显示",
    type: "switch",
    options: [],
    key: "indicator.lastValueMark.show",
    defaultValue: false,
    value: false
  },
  {
    name: "价格轴类型", type: "select", options: [
      { label: "线性轴", value: "normal" },
      { label: "百分比轴", value: "percentage" },
      { label: "对数轴", value: "log" },
    ],
    key: "yAxis.type",
    defaultValue: "normal",
    value: "normal"
  },
  { name: "倒置坐标", type: "switch", options: [], key: "yAxis.reverse", defaultValue: false, value: false },
  { name: "网格线显示", type: "switch", options: [], key: "grid.show", defaultValue: true, value: true },
]);

// 当前股票数据
const currentStockData = ref({
  stockCode: '',
  stockName: '',
  logo:''
});

function onSettingChange(data) {
  settingItems.value = data;
}

function onIndicatorChange(indicator: string, isDel?: boolean, isSub?: boolean) {
  if (isSub) {
    selectedSubIndicator.value = [...selectedSubIndicator.value.filter(item => item != indicator)];
    if (isDel) {

    } else {
      selectedSubIndicator.value.push(indicator)
    }
  } else {
    if (isDel) {
      selectedMainIndicator.value = [...selectedMainIndicator.value.filter(item => item != indicator)]
    } else {
      selectedMainIndicator.value.push(indicator)
    }
  }
};

function openDrawer(stockCode) {
  drawerVisbile.value = true;
}

const leftPagination = ref({
  current: 1,
  total: 0,
});

const rightPagination = ref({
  current: 1,
  total: 0,
});

function searchStockOrSector() {
  searchStockList();
}

let leftScrollPosition = 0;
let leftTicking = false;
let leftBodyClientHeight;
let leftScorllHeight;

let rightScrollPosition = 0;
let rightTicking = false;
let rightBodyClientHeight;
let rightScorllHeight;

function clearScrollData() {
  leftScrollPosition = 0;
  leftTicking = false;
  leftBodyClientHeight=0;
  leftScorllHeight=0;

  rightScrollPosition = 0;
  rightTicking = false;
  rightBodyClientHeight=0;
  rightScorllHeight=0;
}

function handlerLeftBodyScroll(){
  document.getElementById('leftList')?.addEventListener('scroll', (event) => {
      leftScrollPosition = event?.target?.scrollTop;
      leftBodyClientHeight = event?.target?.clientHeight;
      leftScorllHeight = event?.target?.scrollHeight;
      if (!leftTicking) {
        window.requestAnimationFrame(function () {
          let diff = leftScorllHeight - leftScrollPosition - leftBodyClientHeight;
          if(diff<5) {
            leftPagination.value.current = leftPagination.value.current + 1;
            loadMoreLeftData();
          }
          leftTicking = false;
        });

        leftTicking = true;
      }
    }, false);
}

function handlerRightBodyScorll(){
  document.getElementById('rightList')?.addEventListener('scroll', (event) => {
      rightScrollPosition = event?.target?.scrollTop;
      rightBodyClientHeight = event?.target?.clientHeight;
      rightScorllHeight = event?.target?.scrollHeight;
      if (!rightTicking) {
        window.requestAnimationFrame(function () {
          let diff = rightScorllHeight - rightBodyClientHeight - rightScrollPosition;
          if(diff<5) {
            rightPagination.value.current = rightPagination.value.current + 1;
            loadMoreRightata();
          }
          rightTicking = false;
        });

        rightTicking = true;
      }
    }, false);
}

onMounted(() => {
  hBodyWidth.value = (window.innerHeight - 120) + "px";
  searchStockList();
  nextTick(() => {
    handlerLeftBodyScroll();
    handlerRightBodyScorll();
  });
});

onUnmounted(() => {

});

function onSearch() {
  if (sortType.value == 1) {
    rightPagination.value.current = 1;
    searchStockBySectorId();
  } else {
    leftPagination.value.current = 1;
    searchStockList();
  }
}

/**
 * 切换板块和个股radio
 */
function sortTypeChange() {
  leftPagination.value.current = 1;
  rightPagination.value.current = 1;
  clearScrollData();
  searchStockList();
}

async function leftDataItemClick(item) {

  if (item) {
    leftDataSource.value.forEach(data => {
      data['selected'] = false;
    });
    item.selected = true;
    currentSectorName.value = item.name;
  }

  if (sortType.value == 1) {
    rightPagination.value.current = 1;
    await searchStockBySectorId();
    chartViewRef.value.switchStockKline(currentStockData.value.stockCode);
    chartViewRef2.value.switchSectorKlineData(currentSectorName.value);
  } else if (sortType.value == 2) {
    await searchSectorsByStockCode(item.code);
    currentStockData.value = {
      stockCode: item?.code,
      stockName: item?.name,
      logo:item?.logo
    };
    refreshStockInZixuanStatus();
    chartViewRef.value.switchStockKline(currentStockData.value.stockCode);
    chartViewRef2.value.switchSectorKlineData(currentSectorName.value);
  }
}

function rightDataItemClick(item) {
  if (sortType.value == 1) {
    rightDataSource.value.forEach(data => {
      if (item.code == data.code) {
        data['selected'] = true;
      } else {
        data['selected'] = false;
      }
    });
    currentStockData.value = {
      stockCode: item?.code,
      stockName: item?.name,
      logo: item?.logo
    };
    refreshStockInZixuanStatus();
    nextTick(()=> {
      chartViewRef.value.switchStockKline(currentStockData.value.stockCode);
    });
  } else {
    rightDataSource.value.forEach(data => {
      if (item.name == data.name) {
        data['selected'] = true;
      } else {
        data['selected'] = false;
      }
    });
    currentSectorName.value = item.name;
    chartViewRef2.value.switchSectorKlineData(item.name);
  }
}

/**
 * 根据板块id查询个股
 */
async function searchStockBySectorId() {
  var sector = await getSectorByName({ "sectorName": currentSectorName.value });
  var stocks = await getStocksOfDateRange({}, {
    "pageNo": rightPagination.value.current,
    "pageSize": 20,
    "startDate": startTime.value,
    "endDate": endTime.value,
    "keyword": searchStockCode.value,
    "sectorId": sector['id']
  });
  rightDataSource.value = stocks['list'];
  rightDataSource.value.current = stocks['pageNo'];
  rightDataSource.value.total = stocks['count'];
  if (rightDataSource.value && rightDataSource.value.length > 0) {
    rightDataSource.value[0]['selected'] = true;
    currentStockData.value = {
      stockCode: rightDataSource.value[0]?.code,
      stockName: rightDataSource.value[0]?.name,
      logo:rightDataSource.value[0]?.logo
    };
  }
}
/**
 * 根据股票代码查询所属板块
 * 
 * @param stockCode 股票代码
 */
async function searchSectorsByStockCode(stockCode) {
  let sectors = await getSectorOfDateRange({}, {
    "pageNo": 1,
    "pageSize": 20,
    "startDate": startTime.value,
    'endDate': endTime.value,
    "stockCode": stockCode
  });
  rightDataSource.value = sectors['list'];
  rightDataSource.value.current = sectors['pageNo'];
  rightDataSource.value.total = sectors['count'];
  if(rightDataSource.value.length>0){
    rightDataSource.value[0].selected = true;
    currentSectorName.value = rightDataSource.value[0].name
  }
}

async function loadMoreRightata() {
  if(sortType.value==1) {
    showLoading.value = true;
    var sector = await getSectorByName({ "sectorName": currentSectorName.value });
    var stocks = await getStocksOfDateRange({}, {
      "pageNo": rightPagination.value.current,
      "pageSize": 20,
      "startDate": startTime.value,
      "endDate": endTime.value,
      "keyword": searchStockCode.value,
      "sectorId": sector['id']
    });
    rightDataSource.value = rightDataSource.value.concat(stocks['list']);
    rightDataSource.value.current = stocks['pageNo'];
    rightDataSource.value.total = stocks['count'];
    showLoading.value = false;
  }
}

async function loadMoreLeftData() {
  if (sortType.value == 1) {
    showLoading.value = true;
    let sectors = await getSectorOfDateRange({}, {
      "pageNo": leftPagination.value.current,
      "pageSize": 20,
      "startDate": startTime.value,
      'endDate': endTime.value
    });
    leftDataSource.value = leftDataSource.value.concat(sectors['list']);
    leftDataSource.value.current = sectors['pageNo'];
    leftDataSource.value.total = sectors['count'];
    showLoading.value = false;
  } else {
    showLoading.value = true;
    var stocks = await getStocksOfDateRange({}, {
      "pageNo": leftPagination.value.current,
      "pageSize": 20,
      "keyword": searchStockCode.value,
      "startDate": startTime.value,
      "endDate": endTime.value
    });
    leftDataSource.value = leftDataSource.value.concat(stocks['list']);
    leftDataSource.value.current = stocks['pageNo'];
    leftDataSource.value.total = stocks['count'];
    showLoading.value = false;
  }
}

/**
 * 查询个股数据
 */
async function searchStockList() {
  rightDataSource.value = [];
  rightPagination.value.current = 1;
  rightPagination.value.total = 0;

  leftDataSource.value = [];
  leftPagination.value.current = 1;
  leftPagination.value.total = 0;
  
  if (sortType.value == 1) {
    let sectors = await getSectorOfDateRange({}, {
      "pageNo": leftPagination.value.current,
      "pageSize": 20,
      "startDate": startTime.value,
      'endDate': endTime.value
    });
    leftDataSource.value = sectors['list'];
    leftDataSource.value.current = sectors['pageNo'];
    leftDataSource.value.total = sectors['count'];

    currentSectorName.value = sectors['list'][0].name;
    leftDataSource.value[0].selected = true;
    await searchStockBySectorId();
    refreshStockInZixuanStatus();
    chartViewRef.value.switchStockKline(currentStockData.value.stockCode);
    chartViewRef2.value.switchSectorKlineData(currentSectorName.value);

  } else {
    var stocks = await getStocksOfDateRange({}, {
      "pageNo": 1,
      "pageSize": 20,
      "keyword": searchStockCode.value,
      "startDate": startTime.value,
      "endDate": endTime.value
    });
    leftDataSource.value = stocks['list'];
    leftDataSource.value.current = stocks['pageNo'];
    leftDataSource.value.total = stocks['count'];
    leftDataSource.value[0].selected = true;
    if (stocks['list'] && stocks['list'].length > 0) {
      await searchSectorsByStockCode(stocks['list'][0].code);
    }
    currentStockData.value = {
      stockCode: leftDataSource.value[0]?.code,
      stockName: leftDataSource.value[0]?.name,
      logo: leftDataSource.value[0]?.logo
    };
    refreshStockInZixuanStatus();
    chartViewRef.value.switchStockKline(currentStockData.value.stockCode);
    chartViewRef2.value.switchSectorKlineData(currentSectorName.value);
  }
}

/**
 * 加自选
 */
 function addUserStocksClick() {
  let stocks = [currentStockData.value.stockCode];
  addUserStockViewRef.value.showAddUserStockView(2, stocks)
}

async function deleteUserStocksClick(){
  await deleteUserStock({}, {
    'userId': getCurrentUserId(),
    'stockCodes': [currentStockData.value.stockCode]
  });
  stockInZixuanStatus.value = false;
  message.success('删除成功');
}
/**
 * 刷新添加自选/删除自选的状态
 */
function refreshStockInZixuanStatus(){
  stockInUserStock({
      "stockCode": currentStockData.value.stockCode,
      "userId": getCurrentUserId()
    }).then(value=>{
      stockInZixuanStatus.value = value;
  });
}

</script>

<style lang="less" scoped>
body{
  height: 100%;
  overflow-y: scroll;
}
.tableClass {
  color: #025fff
}

.ant-table-measure-row {
  display: none !important;
}

/deep/ .ant-table-tbody>tr>td {
  padding: 6px 12px;
  overflow-wrap: break-word;
}

.ant-table-header .ant-table-cell {
  font-weight: 500;
  color: #9E9E9E;
}

.main-container {
  width: 100%;
  height: 100%;
  display: flex;
  background-color: #fff;
  flex-direction: column;
  padding-top: .5em;
  padding-left: .8em;
  box-sizing: border-box;
  position: absolute;
  left: 0;
  top:0;
  overflow: hidden;
}

.h-header {
  display: flex;
  padding: .5em 0;
}

.h-form {
  display: flex;
  padding: .5em 0;
  box-sizing: border-box;
}

.h-body {
  display: flex;
  flex-direction: row;
  border: 1px solid #f1f1f1;
  position: relative;
  box-shadow: 0 0 5px #ececec;
  height: calc(100% - 100px);
}

.s-table {
  display: flex;
  width: 320px;
  flex-direction: column;
  height: 100%;
}

.s-head {
  flex-direction: row;
  height: 32px;
  padding-left: 0;
  background: #f0f0f0;
  box-sizing: border-box;
  color: #9E9E9E;
}

.s-head>div {
  flex: 1;
  padding: 5px 0px 5px 12px;
}

.s-body {
  flex-direction: column;
  max-height: 99%;
  overflow: scroll;
}

.s-body::-webkit-scrollbar {
  width: 0px;
  height: 0px;
}

.s-body-stock-name {
  color: rgb(2, 95, 255);
  cursor: pointer;
  font-weight: 550;
  font-size: 14px;
  font-family: 'PingFang SC', 'Microsoft YaHei', 'SimSun', 'Arial', sans-serif
}

.left-list {
  flex: 1;
  display: flex;
}

.right-list {
  flex: 1;
  display: flex;
  border-right: 1px solid #f1f1f1;
}

.s-row {
  flex-direction: row;
  padding: 5px 0;
  border: 1px solid #f1f1f1;
  transition: background 1s ease;
  cursor: pointer;
}

.s-row:hover {
  background: #f1f1f1;
}

.s-row.selected {
  background: #f0f5ff;
}

.s-row.selected:hover {
  background: rgb(230, 238, 255);
}

.s-body .s-row>div {
  flex: 1;
  padding: 3px 0px 3px 12px;
}

.ant-table-thead>tr>th {
  color: #ccc !important;
}



.filter-button {
  background-color: #f1f1f1;
  border-radius: 5px;
  border: 0;
  padding: .6em 1.5em;
  font-family: Source Han Sans;
}

.filter-button svg {
  fill: #212121;
}

.filter-button:hover {
  color: #255fff;
}

.filter-button:hover svg {
  fill: #025fff;
}

.filter-button.active {
  background-color: #E9EFFF;
  border-radius: 5px;
  border: 0;
  padding: .6em 1.5em;
  color: #255fff;
}
.k-line-name {
  font-size: 15px;
  font-weight: 700;
  margin: 0 10px;
  padding-right: 5px;
  border-right: 1px solid #e5e5e5;
  height: 20px;
  margin-top: 12px;
}

.k-line-setting {
  display: flex;
  align-items: center;
}

.k-line-setting>.ant-btn {
  border: 0;
  padding: 4px 8px;
}
.period>span {
  line-height: 21px;
  position: relative;
  display: inline-block;
  font-weight: 400;
  white-space: nowrap;
  text-align: center;
  height: 21px;
  width: 26px;
  margin: 0 .2em;
  border-radius: 6px;
  cursor: pointer;
}

.period>span.active {
  background-color: #d0dcfc;
}
.stock-name {
  display: inline-block; 
  margin-left: .5em;
  font-weight: 700;
}

@media screen and (min-width: 1000px) {
  .left-list {
    max-width: 200px !important;
  }
  .right-list {
    max-width: 200px !important;
  }
  .stock-close {
    display: none;
  }
  .stock-name {
    display: none;
  }
}

@media screen and (min-width: 1100px) {
  .left-list {
    max-width: 200px !important;
  }
  .right-list {
    max-width: 200px !important;
  }
  .stock-close {
    display: none;
  }
  .stock-name {
    display: none;
  }
}

@media screen and (min-width: 1228px) {
  .left-list {
    max-width: 200px !important;
  }
  .right-list {
    max-width: 200px !important;
  }
  .stock-close {
    display: none;
  }
  .stock-name {
    display: none;
  }
}

@media screen and (min-width: 1380px) {

  .left-list {
    max-width: 240px !important;
  }
  .right-list {
    max-width: 240px !important;
  }
  .stock-close {
    display: flex;
  }
  .stock-name {
    display: inline-block;
  }
}

@media screen and (min-width: 1520px) {
  .left-list {
    max-width: 300px !important;
  }
  .right-list {
    max-width: 300px !important;
  }
  .stock-close {
    display: flex;
  }
  .stock-name {
    display: inline-block;
  }
}

@media screen and (min-width: 1680px) {
  .left-list {
    max-width: 300px !important;
  }
  .right-list {
    max-width: 300px !important;
  }
  .stock-close {
    display: flex;
  }
  .stock-name {
    display: inline-block;
  }
}

@media screen and (min-width: 1900px) {
  .left-list {
    max-width: 300px !important;
  }
  .right-list {
    max-width: 300px !important;
  }
  .stock-close {
    display: flex;
  }
  .stock-name {
    display: inline-block;
  }
}
</style>